import { Inject, Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository, In } from 'typeorm';
import { OrderOrderEntity } from '../entity/order';
import { OrderGoodsEntity } from '../entity/goods';
import { PluginService } from '../../plugin/service/info';
import { UserInfoEntity } from '../../user/entity/info';
import { OrderShopEntity } from '../entity/shop';
import { AppointmentInfoEntity } from '../../appointment/entity/info';
import { OrderShareEntity } from '../entity/share';
import { OrderMerchantEntity } from '../entity/merchant';
import { OrderQualityEntity } from '../entity/quality';
import { BaseSysUserEntity } from '../../base/entity/sys/user';
import * as fs from 'fs';
import * as path from 'path';
import moment = require('moment');
import { time } from 'console';
import { OrderRefundEntity } from '../entity/refund';
import { OrderTongkangService } from './tongkang';
const crypto = require('crypto');

/**
 * 订单服务
 */
@Provide()
export class OrderRefundService extends BaseService {
  @InjectEntityModel(OrderOrderEntity)
  orderOrderEntity: Repository<OrderOrderEntity>;

  @InjectEntityModel(OrderGoodsEntity)
  orderGoodsEntity: Repository<OrderGoodsEntity>;

  @InjectEntityModel(OrderRefundEntity)
  orderRefundEntity: Repository<OrderRefundEntity>;

  @Inject()
  pluginService: PluginService;

  @Inject()
  orderTongkangService: OrderTongkangService;

  @Inject()
  ctx;

  // 提交退货/换货订单
  async submitRefundExchange(body) {
    console.log(body);
    const order = await this.orderOrderEntity.findOne({
      where: {
        id: body.orderId,
      },
    });
    if (!order) {
      throw new Error('订单不存在');
    }
    if (order.orderProgress != 2 && order.orderProgress != -1) {
      throw new Error('订单状态错误，无法售后/换货');
    }
    // 新增售后/换货订单
    const refundOrder = new OrderRefundEntity();
    // 此处改为在审核通过后绑定新生成的订单的orderNo
    // refundOrder.refundNo = 'RTN-' + order.orderNo;
    refundOrder.proofImages = body.proofImages;
    refundOrder.refundReason = body.reason;
    refundOrder.reasonRemark = body.reasonRemark;
    refundOrder.orderId = order.id; // 订单ID
    refundOrder.updateTime = new Date(); // 更新时间
    refundOrder.refundStatus = 0; // 售后/换货待审核
    if (order.orderProgress != -1) {
      refundOrder.orderId = order.id;
      refundOrder.userId = order.userId;
      refundOrder.refundType = body.refundType;
      refundOrder.totalAmount = order.totalAmount; // 总金额
      refundOrder.refundAmount = order.payAmount; // 退款金额，退款金额为订单支付金额
      refundOrder.shopId = order.shopId; // 商铺ID
      refundOrder.goodIds = order.GoodIds; // 售后/换货商品ID
      await this.orderRefundEntity.save(refundOrder);
    } else if (order.orderProgress == -1) {
      // 先查询现有记录
      const existingRefundOrder = await this.orderRefundEntity.findOne({
        where: {
          orderId: refundOrder.orderId,
        },
      });
      if (existingRefundOrder) {
        // 更新现有记录的字段
        existingRefundOrder.proofImages = refundOrder.proofImages;
        existingRefundOrder.refundReason = refundOrder.refundReason;
        existingRefundOrder.reasonRemark = refundOrder.reasonRemark;
        existingRefundOrder.refundStatus = refundOrder.refundStatus;
        existingRefundOrder.updateTime = refundOrder.updateTime; // 更新时间
        await this.orderRefundEntity.save(existingRefundOrder);
      } else {
        throw new Error('售后/换货订单不存在');
      }
    }
    let orderProgress = -1000; // 默认值，错误
    if (body.refundType == 1) {
      orderProgress = 3; // 退货退款中
    } else if (body.refundType == 2) {
      orderProgress = 4; // 换货中
    }
    // 更改原订单状态
    order.orderProgress = orderProgress;
    await this.orderOrderEntity.save(order);
    // 返回售后/换货订单号
    const resRefundOrder = new OrderRefundEntity();
    resRefundOrder.refundNo = refundOrder.refundNo;
    return true;
  }

  // 根据orderId查询订单售后/换货信息
  async getRefundInfoById(orderId: number) {
    const refundOrder = await this.orderRefundEntity
      .createQueryBuilder('refund')
      .leftJoinAndMapOne(
        'refund.orderGoods',
        OrderGoodsEntity,
        'orderGoods',
        'FIND_IN_SET(orderGoods.id, refund.goodIds)'
      )
      .leftJoinAndMapOne(
        'refund.order',
        OrderOrderEntity,
        'order',
        'refund.orderId = order.id'
      )
      .leftJoinAndMapOne(
        'refund.orderShop',
        OrderShopEntity,
        'orderShop',
        'order.shopId = orderShop.id'
      )
      .leftJoinAndMapOne(
        'refund.orderUser',
        UserInfoEntity,
        'orderUser',
        'order.userId = orderUser.id'
      )
      .where('refund.orderId = :orderId', { orderId })
      .select([
        'refund.id',
        'refund.refundNo',
        'refund.refundType',
        'refund.refundStatus',
        'refund.refundReason',
        'refund.reasonRemark',
        'refund.createTime',
        'refund.proofImages',
        'orderGoods.goodsName',
        'order.orderNo',
        'order.refundAmount',
        'order.createTime',
        'order.orderProgress',
        'order.payAmount',
        'order.orderTime',
        'order.payTime',
        'order.address',
        'order.consignee',
        'order.remark',
        'order.tongkangOrderNo',
        'order.tongkangOrderTime',
        'order.tongkangOrderRequestData',
        'order.payType',
        'order.phone',
        'orderUser.nickName',
        'orderUser.phone',
        'orderShop.name',
      ])
      .getOne();
    console.log(refundOrder);
    if (!refundOrder) {
      return { ...refundOrder, code: 404, msg: '售后/换货订单不存在' };
    }
    return refundOrder;
  }

  // 根据orderId查询订单售后/换货信息
  async getRefundInfoByIdV2(orderId: number) {
    const refundOrder = await this.orderRefundEntity
      .createQueryBuilder('refund')
      .leftJoinAndMapOne(
        'refund.orderGoods',
        OrderGoodsEntity,
        'orderGoods',
        'FIND_IN_SET(orderGoods.id, refund.goodIds)'
      )
      .where('refund.orderId = :orderId', { orderId })
      .select([
        'refund.id',
        'refund.refundNo',
        'refund.refundType',
        'refund.refundReason',
        'refund.reasonRemark',
        'refund.createTime',
        'refund.proofImages',
        'orderGoods.goodsName',
      ])
      .getOne();
    if (!refundOrder) {
      throw new Error('售后/换货订单不存在');
    }
    return refundOrder;
  }

  // 审核售后/换货订单
  async auditRefundExchange(body) {
    console.log(body);
    const refundOrder = await this.orderRefundEntity.findOne({
      where: {
        orderId: body.orderId,
      },
    });
    if (!refundOrder) {
      throw new Error('售后/换货订单不存在');
    }
    if (refundOrder.refundStatus != 0 && refundOrder.refundStatus != -1) {
      throw new Error('售后/换货订单状态错误，无法审核');
    }
    refundOrder.refundStatus = body.auditStatus; // 审核状态
    refundOrder.auditTime = new Date(); // 审核时间
    refundOrder.auditorId = this.ctx.admin.userId; // 审核人ID
    refundOrder.refundNo = moment().format('YYMMDDHHmmssSSS'); // 退款单号

    // 更改原订单状态
    const order = await this.orderOrderEntity.findOne({
      where: {
        id: refundOrder.orderId,
      },
    });
    if (!order) {
      throw new Error('订单不存在');
    } else {
      if (body.auditStatus == -1) {
        order.orderProgress = -1; // 审核拒绝
        order.updateTime = new Date(); // 更新时间
        await this.orderOrderEntity.save(order);
      } else if (body.auditStatus == 1) {
        if (refundOrder.refundType == 1) {
          // 退货审核
          await this.orderOrderEntity.save(order);
          order.orderProgress = 5; // 退货审核通过
        } else if (refundOrder.refundType == 2) {
          await this.orderOrderEntity.save(order);
          // 新订单号
          order.orderNo = moment().format('YYMMDDHHmmssSSS'); // 订单号
          refundOrder.refundNo = order.orderNo; // 售后/换货订单号
          order.id = null; // 新订单ID
          order.orderType = 'refund'; // 订单类型（售后/换货）
          order.orderProgress = 1; // 待下单
          order.createTime = new Date(); // 创建时间
          order.updateTime = new Date(); // 更新时间
          order.shopOrderTime = new Date(); // 店铺下单时间
          const reqData = JSON.parse(JSON.stringify(order.tongkangOrderRequestData));
          reqData.id = order.orderNo;
          order.tongkangOrderRequestData = JSON.stringify(reqData);
          const newOrder = await this.orderOrderEntity.save(order);
          if (newOrder) {
            order.orderProgress = 6; // 换货审核通过
            order.updateTime = new Date(); // 更新时间
            await this.orderOrderEntity.save(order);
            // 新增瞳康订单
            await this.orderTongkangService.addTongkangOrder({
              order_id: newOrder.id,
            });
          } else {
            throw new Error('创建售后/换货订单失败');
          }
        }
      } else {
        throw new Error('审核状态错误');
      }
    }
    console.log(refundOrder);
    await this.orderRefundEntity.save(refundOrder);
    // 返回售后/换货订单号
    const resRefundOrder = new OrderRefundEntity();
    resRefundOrder.refundNo = refundOrder.refundNo;
    return resRefundOrder;
  }
}
